package org.hfy.utils;

import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.awt.Font;
import java.awt.FontFormatException;

/**
 * HTML转PDF工具类
 * 使用OpenHTMLToPDF库 (免费)
 * 
 * @author hfy
 * @version 1.0
 */
@Slf4j
public class HtmlToPdfUtils {

    /**
     * 将HTML字符串转换为PDF字节数组
     * 
     * @param htmlContent HTML内容
     * @return PDF字节数组
     */
    public static byte[] convertHtmlToPdf(String htmlContent) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            log.info("开始将HTML转换为PDF");
            
            // 预处理HTML内容，确保XHTML兼容性和中文字体支持
            String processedHtml = preprocessHtmlForPdf(htmlContent);
            
            // 创建PDF渲染器构建器
            PdfRendererBuilder builder = new PdfRendererBuilder();
            
            // 设置HTML内容
            builder.withHtmlContent(processedHtml, null);
            
            // 设置输出流
            builder.toStream(outputStream);
            
            // 配置页面设置（单页显示）
            configurePageSettings(builder);
            
            // 配置中文字体支持
            configureFonts(builder);
            
            // 运行渲染
            builder.run();
            
            byte[] pdfBytes = outputStream.toByteArray();
            log.info("HTML转PDF成功，PDF大小: {} bytes", pdfBytes.length);
            
            return pdfBytes;
            
        } catch (IOException e) {
            log.error("HTML转PDF失败: {}", e.getMessage(), e);
            throw new RuntimeException("HTML转PDF失败: " + e.getMessage(), e);
        } catch (Exception e) {
            log.error("HTML转PDF出现未知错误: {}", e.getMessage(), e);
            throw new RuntimeException("HTML转PDF失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 配置页面设置（单页显示）
     * 
     * @param builder PDF渲染器构建器
     */
    private static void configurePageSettings(PdfRendererBuilder builder) {
        try {
            log.debug("开始配置PDF页面设置为激进单页显示");
            
            // 启用快速模式
            builder.useFastMode();
            
            // 设置页面尺寸为A2横向（594mm x 420mm）
            // A2横向：420mm高 x 594mm宽
            // 转换为点：1mm ≈ 2.83点
            float pageWidth = 594 * 2.83f;   // 约1681点
            float pageHeight = 420 * 2.83f;  // 约1189点
            
            // 尝试设置自定义页面大小
            try {
                // 由于API限制，主要依赖CSS的@page规则
                log.debug("使用CSS @page规则设置A2横向页面: {}x{} 点", pageWidth, pageHeight);
            } catch (Exception e) {
                log.debug("页面大小设置异常，将依赖CSS @page规则: {}", e.getMessage());
            }
            
            log.info("PDF页面设置配置完成：激进单页显示模式，A2横向，65%缩放");
            
        } catch (Exception e) {
            log.warn("页面设置配置失败，将使用默认设置: {}", e.getMessage());
        }
    }
    
    /**
     * 配置中文字体支持
     * 
     * @param builder PDF渲染器构建器
     */
    private static void configureFonts(PdfRendererBuilder builder) {
        try {
            log.debug("开始配置中文字体");
            
            // 尝试使用系统字体
            String os = System.getProperty("os.name").toLowerCase();
            
            if (os.contains("windows")) {
                // Windows系统字体
                configureFontFamily(builder, "SimSun", "C:/Windows/Fonts/simsun.ttc", "serif");
                configureFontFamily(builder, "Microsoft YaHei", "C:/Windows/Fonts/msyh.ttc", "sans-serif");
                configureFontFamily(builder, "SimHei", "C:/Windows/Fonts/simhei.ttf", "sans-serif");
            } else if (os.contains("mac")) {
                // macOS系统字体
                configureFontFamily(builder, "PingFang SC", "/System/Library/Fonts/PingFang.ttc", "sans-serif");
                configureFontFamily(builder, "Heiti SC", "/System/Library/Fonts/STHeiti Light.ttc", "sans-serif");
            } else {
                // Linux系统字体
                configureFontFamily(builder, "WenQuanYi Micro Hei", "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", "sans-serif");
                configureFontFamily(builder, "Noto Sans CJK SC", "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", "sans-serif");
            }
            
            log.info("中文字体配置完成");
            
        } catch (Exception e) {
            log.warn("字体配置失败，将使用默认字体: {}", e.getMessage());
        }
    }
    
    /**
     * 配置字体族
     * 
     * @param builder PDF渲染器构建器
     * @param fontFamily 字体族名称
     * @param fontPath 字体文件路径
     * @param genericFamily 通用字体族
     */
    private static void configureFontFamily(PdfRendererBuilder builder, String fontFamily, String fontPath, String genericFamily) {
        try {
            java.io.File fontFile = new java.io.File(fontPath);
            if (fontFile.exists()) {
                // 正常字体
                builder.useFont(fontFile, fontFamily);
                log.debug("成功配置字体: {} -> {}", fontFamily, fontPath);
            } else {
                log.debug("字体文件不存在: {}", fontPath);
            }
        } catch (Exception e) {
            log.debug("配置字体失败: {} - {}", fontFamily, e.getMessage());
        }
    }
    
    /**
     * 预处理HTML内容，确保XHTML兼容性和中文字体支持
     * 
     * @param htmlContent 原始HTML内容
     * @return 处理后的HTML内容
     */
    private static String preprocessHtmlForPdf(String htmlContent) {
        if (htmlContent == null) {
            return "";
        }
        
        // 修复常见的XHTML兼容性问题
        String processed = htmlContent
            // 修复meta标签
            .replaceAll("<meta([^>]*?)(?<!/)>", "<meta$1 />")
            // 修复br标签
            .replaceAll("<br(?:\\s[^>]*)?>", "<br />")
            // 修复hr标签
            .replaceAll("<hr(?:\\s[^>]*)?>", "<hr />")
            // 修复input标签
            .replaceAll("<input([^>]*?)(?<!/)>", "<input$1 />")
            // 修复img标签
            .replaceAll("<img([^>]*?)(?<!/)>", "<img$1 />")
            // 修复link标签
            .replaceAll("<link([^>]*?)(?<!/)>", "<link$1 />")
            // 修复HTML实体问题 - 将&nbsp;替换为普通空格
            .replace("&nbsp;", " ")
            // 如果有其他HTML实体问题，也可以在这里添加
            .replace("&lt;", "<")
            .replace("&gt;", ">")
            .replace("&amp;", "&")
            .replace("&quot;", "\"")
            .replace("&apos;", "'");
        
        // 确保CSS中包含适当的中文字体回退
        processed = enhanceFontSupport(processed);
        
        log.debug("HTML预处理完成");
        return processed;
    }
    
    /**
     * 增强字体支持，确保中文字符正确显示
     * 
     * @param htmlContent HTML内容
     * @return 增强后的HTML内容
     */
    private static String enhanceFontSupport(String htmlContent) {
        // 查找style标签并增强字体定义
        if (htmlContent.contains("<style>")) {
            // 为简化的HTML模板添加字体支持和PDF优化，使用表格布局代替flex确保兼容性
            String fontAndPdfOptimization = "\n" +
                "        /* 字体回退定义 */\n" +
                "        * {\n" +
                "            font-family: 'Microsoft YaHei', 'SimSun', 'SimHei', 'PingFang SC', 'Heiti SC', 'WenQuanYi Micro Hei', sans-serif !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* PDF单页严格设置 */\n" +
                "        @page {\n" +
                "            size: A4 landscape !important;\n" +
                "            margin: 3mm !important;\n" +
                "        }\n" +
                "        \n" +
                "        html, body {\n" +
                "            font-family: 'Microsoft YaHei', 'SimSun', 'SimHei', 'PingFang SC', 'Heiti SC', 'WenQuanYi Micro Hei', sans-serif !important;\n" +
                "            margin: 0 !important;\n" +
                "            padding: 0 !important;\n" +
                "            font-size: 8px !important;\n" +
                "            height: auto !important;\n" +
                "            page-break-inside: avoid !important;\n" +
                "        }\n" +
                "        \n" +
                "        .container {\n" +
                "            transform: scale(0.7) !important;\n" +
                "            transform-origin: top left !important;\n" +
                "            width: 142.857% !important;\n" +
                "            height: auto !important;\n" +
                "            margin: 0 !important;\n" +
                "            padding: 0 !important;\n" +
                "            page-break-inside: avoid !important;\n" +
                "            page-break-after: avoid !important;\n" +
                "            overflow: hidden !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 使用表格布局替代flex确保左右排版兼容性 */\n" +
                "        .contract-info {\n" +
                "            display: table !important;\n" +
                "            width: 100% !important;\n" +
                "            table-layout: fixed !important;\n" +
                "            border-collapse: collapse !important;\n" +
                "            padding: 6px !important;\n" +
                "            margin: 0 !important;\n" +
                "        }\n" +
                "        \n" +
                "        .client-info, .contract-details {\n" +
                "            display: table-cell !important;\n" +
                "            width: 50% !important;\n" +
                "            vertical-align: top !important;\n" +
                "            padding: 3px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .client-info {\n" +
                "            border-right: 1px solid #000 !important;\n" +
                "            padding-right: 6px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .contract-details {\n" +
                "            padding-left: 6px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .info-row {\n" +
                "            display: table !important;\n" +
                "            width: 100% !important;\n" +
                "            margin-bottom: 2px !important;\n" +
                "            table-layout: fixed !important;\n" +
                "        }\n" +
                "        \n" +
                "        .info-label {\n" +
                "            display: table-cell !important;\n" +
                "            width: 60px !important;\n" +
                "            font-size: 7px !important;\n" +
                "            font-weight: bold !important;\n" +
                "            vertical-align: top !important;\n" +
                "        }\n" +
                "        \n" +
                "        .info-value {\n" +
                "            display: table-cell !important;\n" +
                "            font-size: 7px !important;\n" +
                "            vertical-align: top !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 签名区域表格布局 */\n" +
                "        .signature-area {\n" +
                "            display: table !important;\n" +
                "            width: 100% !important;\n" +
                "            table-layout: fixed !important;\n" +
                "            border-collapse: collapse !important;\n" +
                "            padding: 6px !important;\n" +
                "            margin: 0 !important;\n" +
                "        }\n" +
                "        \n" +
                "        .signature-box {\n" +
                "            display: table-cell !important;\n" +
                "            width: 50% !important;\n" +
                "            vertical-align: top !important;\n" +
                "            padding: 3px !important;\n" +
                "            font-size: 7px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .signature-box:first-child {\n" +
                "            border-right: 1px solid #000 !important;\n" +
                "            padding-right: 6px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .signature-box:last-child {\n" +
                "            padding-left: 6px !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 头部压缩 */\n" +
                "        header {\n" +
                "            padding: 8px 6px !important;\n" +
                "        }\n" +
                "        \n" +
                "        header h1 {\n" +
                "            font-size: 14px !important;\n" +
                "            margin-bottom: 4px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .company-info {\n" +
                "            font-size: 8px !important;\n" +
                "            line-height: 1.2 !important;\n" +
                "        }\n" +
                "        \n" +
                "        .section-title {\n" +
                "            font-size: 10px !important;\n" +
                "            margin-bottom: 4px !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 表格极致压缩 */\n" +
                "        .table-wrapper {\n" +
                "            padding: 4px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .products-table {\n" +
                "            font-size: 5px !important;\n" +
                "            margin: 2px 0 !important;\n" +
                "            page-break-inside: avoid !important;\n" +
                "        }\n" +
                "        \n" +
                "        .products-table th,\n" +
                "        .products-table td {\n" +
                "            padding: 1px !important;\n" +
                "            font-size: 5px !important;\n" +
                "            line-height: 1 !important;\n" +
                "        }\n" +
                "        \n" +
                "        .products-table th {\n" +
                "            font-size: 5px !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 条款区域极致压缩 */\n" +
                "        .terms-section {\n" +
                "            font-size: 6px !important;\n" +
                "            padding: 4px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .terms-section h3 {\n" +
                "            font-size: 7px !important;\n" +
                "            margin: 2px 0 1px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .terms-section p {\n" +
                "            line-height: 1 !important;\n" +
                "            margin-bottom: 1px !important;\n" +
                "            font-size: 6px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .signature-title {\n" +
                "            font-size: 8px !important;\n" +
                "            margin-bottom: 4px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .signature-line {\n" +
                "            margin-top: 15px !important;\n" +
                "            padding-top: 2px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .controls {\n" +
                "            display: none !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 强制单页显示 */\n" +
                "        * {\n" +
                "            page-break-inside: avoid !important;\n" +
                "        }\n" +
                "        \n" +
                "        @media print {\n" +
                "            body { \n" +
                "                -webkit-print-color-adjust: exact !important;\n" +
                "                color-adjust: exact !important;\n" +
                "            }\n" +
                "        }\n";
            
            htmlContent = htmlContent.replace("<style>", "<style>" + fontAndPdfOptimization);
        }
        
        return htmlContent;
    }
    
    /**
     * 将HTML字符串转换为PDF字节数组（带错误处理）
     * 
     * @param htmlContent HTML内容
     * @return PDF字节数组，失败时返回错误PDF
     */
    public static byte[] convertHtmlToPdfSafe(String htmlContent) {
        try {
            return convertHtmlToPdf(htmlContent);
        } catch (Exception e) {
            log.error("HTML转PDF失败，生成错误PDF: {}", e.getMessage());
            return generateErrorPdf(e.getMessage());
        }
    }

    /**
     * 将送货单HTML转换为PDF字节数组（送货单专用优化）
     * 
     * @param htmlContent HTML内容
     * @return PDF字节数组，失败时返回错误PDF
     */
    public static byte[] convertDeliveryNoteHtmlToPdf(String htmlContent) {
        try {
            // 预处理HTML内容，应用送货单专用样式
            String processedHtml = preprocessDeliveryNoteHtmlForPdf(htmlContent);
            
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PdfRendererBuilder builder = new PdfRendererBuilder();
            
            // 配置基础设置
            builder.withHtmlContent(processedHtml, null);
            builder.toStream(outputStream);
            builder.useFastMode();
            
            // 配置页面设置
            configurePageSettings(builder);
            
            // 配置中文字体
            configureFonts(builder);
            
            // 渲染PDF
            builder.run();
            
            byte[] result = outputStream.toByteArray();
            log.info("送货单PDF生成成功，大小: {} bytes", result.length);
            
            return result;
            
        } catch (Exception e) {
            log.error("送货单HTML转PDF失败: {}", e.getMessage(), e);
            return generateErrorPdf("送货单生成失败: " + e.getMessage());
        }
    }

    /**
     * 预处理送货单HTML内容，确保XHTML兼容性和PDF优化
     * 
     * @param htmlContent 原始HTML内容
     * @return 处理后的HTML内容
     */
    private static String preprocessDeliveryNoteHtmlForPdf(String htmlContent) {
        if (htmlContent == null) {
            return "";
        }
        
        // 修复常见的XHTML兼容性问题
        String processed = htmlContent
            .replaceAll("<meta([^>]*?)(?<!/)>", "<meta$1 />")
            .replaceAll("<br(?:\\s[^>]*)?>", "<br />")
            .replaceAll("<hr(?:\\s[^>]*)?>", "<hr />")
            .replaceAll("<input([^>]*?)(?<!/)>", "<input$1 />")
            .replaceAll("<img([^>]*?)(?<!/)>", "<img$1 />")
            .replaceAll("<link([^>]*?)(?<!/)>", "<link$1 />")
            // 修复HTML实体问题 - 将&nbsp;替换为普通空格
            .replace("&nbsp;", " ")
            .replace("&lt;", "<")
            .replace("&gt;", ">")
            .replace("&amp;", "&")
            .replace("&quot;", "\"")
            .replace("&apos;", "'");
        
        // 应用送货单专用的字体和布局优化
        processed = enhanceDeliveryNoteFontSupport(processed);
        
        log.debug("送货单HTML预处理完成");
        return processed;
    }

    /**
     * 为送货单增强字体支持和布局优化
     * 
     * @param htmlContent HTML内容
     * @return 增强后的HTML内容
     */
    private static String enhanceDeliveryNoteFontSupport(String htmlContent) {
        // 查找style标签并增强字体定义
        if (htmlContent.contains("<style>")) {
            // 送货单专用的PDF优化CSS
            String deliveryOptimization = "\n" +
                "        /* 送货单字体回退定义 */\n" +
                "        * {\n" +
                "            font-family: 'Microsoft YaHei', 'SimSun', 'SimHei', 'PingFang SC', 'Heiti SC', 'WenQuanYi Micro Hei', sans-serif !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 送货单页面设置 */\n" +
                "        @page {\n" +
                "            size: A4 portrait !important;\n" +
                "            margin: 8mm !important;\n" +
                "        }\n" +
                "        \n" +
                "        html, body {\n" +
                "            font-family: 'Microsoft YaHei', 'SimSun', 'SimHei', 'PingFang SC', 'Heiti SC', 'WenQuanYi Micro Hei', sans-serif !important;\n" +
                "            margin: 0 !important;\n" +
                "            padding: 8px !important;\n" +
                "            font-size: 11px !important;\n" +
                "            line-height: 1.3 !important;\n" +
                "            page-break-inside: avoid !important;\n" +
                "        }\n" +
                "        \n" +
                "        .container {\n" +
                "            margin: 0 !important;\n" +
                "            padding: 15px !important;\n" +
                "            page-break-inside: avoid !important;\n" +
                "            overflow: visible !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 送货单头部优化 */\n" +
                "        .company-header {\n" +
                "            margin-bottom: 12px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .company-name {\n" +
                "            font-size: 16px !important;\n" +
                "            margin-bottom: 5px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .company-address {\n" +
                "            font-size: 11px !important;\n" +
                "            margin-bottom: 15px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .document-title {\n" +
                "            font-size: 20px !important;\n" +
                "            padding: 10px 0 !important;\n" +
                "            margin-bottom: 15px !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 送货信息区域表格布局优化 */\n" +
                "        .delivery-info {\n" +
                "            display: table !important;\n" +
                "            width: 100% !important;\n" +
                "            table-layout: fixed !important;\n" +
                "            margin-bottom: 15px !important;\n" +
                "            font-size: 11px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .receiver-info {\n" +
                "            display: table-cell !important;\n" +
                "            width: 60% !important;\n" +
                "            vertical-align: top !important;\n" +
                "            padding-right: 15px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .document-info {\n" +
                "            display: table-cell !important;\n" +
                "            width: 40% !important;\n" +
                "            vertical-align: top !important;\n" +
                "            text-align: right !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 产品表格优化 */\n" +
                "        .products-table {\n" +
                "            font-size: 9px !important;\n" +
                "            margin-bottom: 15px !important;\n" +
                "            page-break-inside: avoid !important;\n" +
                "        }\n" +
                "        \n" +
                "        .products-table th {\n" +
                "            padding: 5px 2px !important;\n" +
                "            font-size: 9px !important;\n" +
                "            font-weight: bold !important;\n" +
                "        }\n" +
                "        \n" +
                "        .products-table td {\n" +
                "            padding: 3px 2px !important;\n" +
                "            font-size: 9px !important;\n" +
                "            line-height: 1.2 !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 备注区域 */\n" +
                "        .notes {\n" +
                "            margin-bottom: 15px !important;\n" +
                "            padding: 10px !important;\n" +
                "            font-size: 10px !important;\n" +
                "            line-height: 1.4 !important;\n" +
                "        }\n" +
                "        \n" +
                "        .copy-info {\n" +
                "            margin-bottom: 15px !important;\n" +
                "            font-size: 11px !important;\n" +
                "            padding: 6px 0 !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 签名区域表格布局 */\n" +
                "        .signature-area {\n" +
                "            display: table !important;\n" +
                "            width: 100% !important;\n" +
                "            table-layout: fixed !important;\n" +
                "            margin-top: 15px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .signature-box {\n" +
                "            display: table-cell !important;\n" +
                "            width: 50% !important;\n" +
                "            vertical-align: top !important;\n" +
                "            padding: 5px !important;\n" +
                "            font-size: 10px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .signature-box:first-child {\n" +
                "            border-right: 1px solid #000 !important;\n" +
                "            padding-right: 12px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .signature-box:last-child {\n" +
                "            padding-left: 12px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .signature-box p {\n" +
                "            margin-bottom: 10px !important;\n" +
                "            padding-bottom: 5px !important;\n" +
                "            font-size: 10px !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 隐藏打印控制按钮 */\n" +
                "        .print-controls {\n" +
                "            display: none !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 强制单页显示 */\n" +
                "        * {\n" +
                "            page-break-inside: avoid !important;\n" +
                "        }\n" +
                "        \n" +
                "        @media print {\n" +
                "            body { \n" +
                "                -webkit-print-color-adjust: exact !important;\n" +
                "                color-adjust: exact !important;\n" +
                "            }\n" +
                "        }\n";
            
            htmlContent = htmlContent.replace("<style>", "<style>" + deliveryOptimization);
        }
        
        return htmlContent;
    }

    /**
     * 将标签HTML转换为PDF字节数组（标签专用优化）
     * 
     * @param htmlContent HTML内容
     * @return PDF字节数组，失败时返回错误PDF
     */
    public static byte[] convertLabelHtmlToPdf(String htmlContent) {
        try {
            // 预处理HTML内容，应用标签专用样式
            String processedHtml = preprocessLabelHtmlForPdf(htmlContent);
            
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PdfRendererBuilder builder = new PdfRendererBuilder();
            
            // 配置基础设置
            builder.withHtmlContent(processedHtml, null);
            builder.toStream(outputStream);
            builder.useFastMode();
            
            // 配置页面设置
            configurePageSettings(builder);
            
            // 配置中文字体
            configureFonts(builder);
            
            // 渲染PDF
            builder.run();
            
            byte[] result = outputStream.toByteArray();
            log.info("标签PDF生成成功，大小: {} bytes", result.length);
            
            return result;
            
        } catch (Exception e) {
            log.error("标签HTML转PDF失败: {}", e.getMessage(), e);
            return generateErrorPdf("标签生成失败: " + e.getMessage());
        }
    }

    /**
     * 预处理标签HTML内容，确保XHTML兼容性和PDF优化
     * 
     * @param htmlContent 原始HTML内容
     * @return 处理后的HTML内容
     */
    private static String preprocessLabelHtmlForPdf(String htmlContent) {
        if (htmlContent == null) {
            return "";
        }
        
        // 修复常见的XHTML兼容性问题
        String processed = htmlContent
            .replaceAll("<meta([^>]*?)(?<!/)>", "<meta$1 />")
            .replaceAll("<br(?:\\s[^>]*)?>", "<br />")
            .replaceAll("<hr(?:\\s[^>]*)?>", "<hr />")
            .replaceAll("<input([^>]*?)(?<!/)>", "<input$1 />")
            .replaceAll("<img([^>]*?)(?<!/)>", "<img$1 />")
            .replaceAll("<link([^>]*?)(?<!/)>", "<link$1 />")
            // 修复HTML实体问题 - 将&nbsp;替换为普通空格
            .replace("&nbsp;", " ")
            .replace("&lt;", "<")
            .replace("&gt;", ">")
            .replace("&amp;", "&")
            .replace("&quot;", "\"")
            .replace("&apos;", "'");
        
        // 应用标签专用的字体和布局优化
        processed = enhanceLabelFontSupport(processed);
        
        log.debug("标签HTML预处理完成");
        return processed;
    }

    /**
     * 为标签增强字体支持和布局优化
     * 
     * @param htmlContent HTML内容
     * @return 增强后的HTML内容
     */
    private static String enhanceLabelFontSupport(String htmlContent) {
        // 查找style标签并增强字体定义
        if (htmlContent.contains("<style>")) {
            // 标签专用的PDF优化CSS
            String labelOptimization = "\n" +
                "        /* 标签字体回退定义 */\n" +
                "        * {\n" +
                "            font-family: 'Microsoft YaHei', 'SimSun', 'SimHei', 'PingFang SC', 'Heiti SC', 'WenQuanYi Micro Hei', sans-serif !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 标签页面设置 */\n" +
                "        @page {\n" +
                "            size: A4 portrait !important;\n" +
                "            margin: 15mm !important;\n" +
                "        }\n" +
                "        \n" +
                "        html, body {\n" +
                "            font-family: 'Microsoft YaHei', 'SimSun', 'SimHei', 'PingFang SC', 'Heiti SC', 'WenQuanYi Micro Hei', sans-serif !important;\n" +
                "            margin: 0 !important;\n" +
                "            padding: 10px !important;\n" +
                "            background: white !important;\n" +
                "            page-break-inside: avoid !important;\n" +
                "        }\n" +
                "        \n" +
                "        .container {\n" +
                "            max-width: 300px !important;\n" +
                "            width: 300px !important;\n" +
                "            margin: 0 auto !important;\n" +
                "            padding: 0 !important;\n" +
                "            page-break-inside: avoid !important;\n" +
                "        }\n" +
                "        \n" +
                "        .label-card {\n" +
                "            max-width: 250px !important;\n" +
                "            width: 250px !important;\n" +
                "            margin: 0 auto !important;\n" +
                "            border: 2px solid #000 !important;\n" +
                "            border-radius: 4px !important;\n" +
                "            page-break-inside: avoid !important;\n" +
                "            overflow: visible !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 标签头部 */\n" +
                "        .label-header {\n" +
                "            background: #2c3e50 !important;\n" +
                "            color: white !important;\n" +
                "            padding: 6px !important;\n" +
                "            text-align: center !important;\n" +
                "        }\n" +
                "        \n" +
                "        .label-header h2 {\n" +
                "            font-size: 12px !important;\n" +
                "            letter-spacing: 1px !important;\n" +
                "            font-weight: bold !important;\n" +
                "            margin: 0 !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 标签内容 */\n" +
                "        .label-content {\n" +
                "            padding: 8px 10px !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 信息行表格布局 */\n" +
                "        .info-row {\n" +
                "            display: table !important;\n" +
                "            width: 100% !important;\n" +
                "            padding: 3px 0 !important;\n" +
                "            border-bottom: 1px solid #e0e0e0 !important;\n" +
                "            table-layout: fixed !important;\n" +
                "        }\n" +
                "        \n" +
                "        .info-row:last-child {\n" +
                "            border-bottom: none !important;\n" +
                "        }\n" +
                "        \n" +
                "        .info-label {\n" +
                "            display: table-cell !important;\n" +
                "            font-weight: bold !important;\n" +
                "            color: #333 !important;\n" +
                "            font-size: 9px !important;\n" +
                "            text-align: left !important;\n" +
                "            width: 35% !important;\n" +
                "            vertical-align: middle !important;\n" +
                "        }\n" +
                "        \n" +
                "        .info-value {\n" +
                "            display: table-cell !important;\n" +
                "            font-weight: normal !important;\n" +
                "            color: #000 !important;\n" +
                "            font-size: 9px !important;\n" +
                "            text-align: left !important;\n" +
                "            width: 65% !important;\n" +
                "            vertical-align: middle !important;\n" +
                "            padding-left: 4px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .highlight {\n" +
                "            color: #e63946 !important;\n" +
                "            font-weight: bold !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 装饰角 */\n" +
                "        .corner-decoration {\n" +
                "            position: absolute !important;\n" +
                "            width: 6px !important;\n" +
                "            height: 6px !important;\n" +
                "        }\n" +
                "        \n" +
                "        .corner-tl {\n" +
                "            top: 3px !important;\n" +
                "            left: 3px !important;\n" +
                "            border-top: 1px solid #adb5bd !important;\n" +
                "            border-left: 1px solid #adb5bd !important;\n" +
                "        }\n" +
                "        \n" +
                "        .corner-tr {\n" +
                "            top: 3px !important;\n" +
                "            right: 3px !important;\n" +
                "            border-top: 1px solid #adb5bd !important;\n" +
                "            border-right: 1px solid #adb5bd !important;\n" +
                "        }\n" +
                "        \n" +
                "        .corner-bl {\n" +
                "            bottom: 3px !important;\n" +
                "            left: 3px !important;\n" +
                "            border-bottom: 1px solid #adb5bd !important;\n" +
                "            border-left: 1px solid #adb5bd !important;\n" +
                "        }\n" +
                "        \n" +
                "        .corner-br {\n" +
                "            bottom: 3px !important;\n" +
                "            right: 3px !important;\n" +
                "            border-bottom: 1px solid #adb5bd !important;\n" +
                "            border-right: 1px solid #adb5bd !important;\n" +
                "        }\n" +
                "        \n" +
                "        /* 强制单页显示 */\n" +
                "        * {\n" +
                "            page-break-inside: avoid !important;\n" +
                "        }\n" +
                "        \n" +
                "        @media print {\n" +
                "            body { \n" +
                "                -webkit-print-color-adjust: exact !important;\n" +
                "                color-adjust: exact !important;\n" +
                "                background: white !important;\n" +
                "            }\n" +
                "        }\n";
            
            htmlContent = htmlContent.replace("<style>", "<style>" + labelOptimization);
        }
        
        return htmlContent;
    }
    
    /**
     * 生成错误信息PDF
     * 
     * @param errorMessage 错误信息
     * @return 错误PDF字节数组
     */
    private static byte[] generateErrorPdf(String errorMessage) {
        String errorHtml = "<!DOCTYPE html>" +
                "<html>" +
                "<head>" +
                "<meta charset='UTF-8'>" +
                "<title>PDF生成错误</title>" +
                "<style>" +
                "body { font-family: 'Microsoft YaHei', sans-serif; padding: 50px; text-align: center; }" +
                ".error { color: #e74c3c; font-size: 18px; margin: 20px 0; }" +
                ".message { color: #7f8c8d; font-size: 14px; }" +
                "</style>" +
                "</head>" +
                "<body>" +
                "<h1>PDF生成失败</h1>" +
                "<div class='error'>抱歉，PDF生成过程中出现错误</div>" +
                "<div class='message'>错误信息：" + errorMessage + "</div>" +
                "<div class='message'>请联系系统管理员或稍后重试</div>" +
                "</body>" +
                "</html>";
        
        try {
            return convertHtmlToPdf(errorHtml);
        } catch (Exception fallbackError) {
            log.error("生成错误PDF也失败了: {}", fallbackError.getMessage());
            // 返回一个简单的字符串作为最后的备用方案
            return ("PDF生成失败: " + errorMessage).getBytes();
        }
    }
} 